import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:palmf_hid/common/entities/can_select_results_entity.dart';
import 'package:palmf_hid/common/entities/event/result_refresh_event.dart';
import 'package:palmf_hid/common/services/Db.dart';
import 'package:palmf_hid/common/utils/my_log_util.dart';
import 'package:palmf_hid/common/utils/utils.dart';
import 'package:palmf_hid/pages/main/home/home_logic.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import 'check_state.dart';
import 'sync_data_select/sync_data_select_view.dart';

class CheckLogic extends GetxController {
  final CheckState state = CheckState();
  final homeLogic = Get.put(HomeLogic());
  final GlobalKey refresherKey = GlobalKey();
  final RefreshController refreshController =
      RefreshController(initialRefresh: true);
  final TextEditingController deviceNoTextEditingController =
      TextEditingController();
  final TextEditingController projectTextEditingController =
      TextEditingController();

  @override
  void onReady() {
    // TODO: implement onReady
    super.onReady();
    registerEventBus();
  }

  bool _isDestroy = false;

  ///注册事件总线
  void registerEventBus() {
    resultRefreshEventInEventBus.on<ResultRefreshEvent>().listen((event) {
      if (_isDestroy) {
        return;
      }
      refreshController.requestRefresh();
    });
  }

  @override
  void dispose() {
    super.dispose();
    _isDestroy = true;
  }

  @override
  void onClose() {
    // TODO: implement onClose
    super.onClose();
  }

  void handleDeleteDeviceTestData() {
    homeLogic.sendDeleteAllTestDataOrder();
  }

  void handleGetDeviceTimeData() {
    homeLogic.sendGetDeviceTimeOrder();
  }

  void handleSetDeviceTimeData() {
    homeLogic.sendSetTimeOrder();
  }

  void handleSyncAllDevice() {
    showDialog(
        context: Get.context!,
        useSafeArea: true,
        barrierDismissible: true,
        builder: (ctx) {
          return SyncDataSelectPage();
        }).then((value) {
      if (null != value) {
        if (null == value) {
          return;
        }
        if (value == -1) {
          homeLogic.sendSyncAllDataOrder();
        } else {
          homeLogic.sendSyncDataOrderByUserNum(value);
        }
      }
    });
  }

  void handleSendClearQrCodeOrder() {
    homeLogic.sendClearQrCodeOrder();
  }

  void handleSelect(int index) {
    state.historyResultList[index].selected =
        !state.historyResultList[index].selected;

    var allS = state.historyResultList.where((e) {
      return e.selected;
    }).toList();

    if (allS.length == 0) {
      state.allSelect = false;
    }
    if (allS.length > 3) {
      MyToastUtil.show("最多可选3条记录");
      return;
    }

    var allNotS = state.historyResultList.where((e) {
      return !e.selected;
    }).toList();

    if (allNotS.length == 0) {
      state.allSelect = true;
    }
    state.historyResultList.refresh();
  }

//刷新
  Future<void> onRefresh() async {
    state.dataState = "数据加载中...";
    getLibraryList(isRefresh: true).then((value) {
      refreshController.requestRefresh();
      refreshController.refreshCompleted(resetFooterState: true);
    }).catchError((e) {
      MyLogUtil().i(e);
      refreshController.refreshFailed();
    });
  }

  // 拉取数据
  Future<void> getLibraryList({bool isRefresh = false}) async {
    if (isRefresh == true) {
      state.historyResultList.clear();
      MyLogUtil().i("清空了吗？  ${state.historyResultList.length}");

      ///本地数据库数据
      var localData = await DbService.to.allResultDataByDeviceNoOrProject(
          state.deviceNo, state.project, state.checkTime);

      List<CanSelectResultsEntity> selectedResultsLocal = [];
      localData.forEach((e) {
        CanSelectResultsEntity entity = CanSelectResultsEntity();
        entity.results = e;

        selectedResultsLocal.add(entity);
      });
      if (selectedResultsLocal.isEmpty) {
        state.dataState = "没有数据";
      } else {
        state.dataState = "数据加载完成";
      }
      state.historyResultList.addAll(selectedResultsLocal);
    }
  }

//删除本地数据
  void handleDeleteDb() {
    DbService.to.removeAllHistory().then((value) {
      MyToastUtil.show("删除成功");
      refreshController.requestRefresh();
    });
  }
}
